<!DOCTYPE html>
<html>
<head>
	<title>球碰撞</title>
	<!-- 原理，极限是两球外切，用三角形勾股定理判断 -->
	<style type="text/css">
	#big{
		width: 800px;
		height: 800px;
		border: 1px solid black;
		position: relative;
	}
	#small{
		width: 20px;
		height: 20px;
		background-color: gray;
		position: absolute;
		border-radius: 50%;
		text-align: center;
	}
	#small2{
		width: 100px;
		height: 100px;
		background-color: red;
		position: absolute;
		top: 100px;
		left: 300px;
		border-radius: 50%;
		text-align: center;
	}
	#small3{
		width: 50px;
		height: 50px;
		background-color: red;
		position: absolute;
		top: 400px;
		left: 50px;
		border-radius: 50%;
		text-align: center;
	}
	</style>
</head>
<body>
<div id="big">
	<div id="small">small</div>
	<div class="st" id="small2">small2</div>
	<div class="st" id="small3">small3</div>
</div>
</body>
<script type="text/javascript">
	
	var big = document.getElementById('big');
	var small = document.getElementById('small');
	var small2 = document.getElementById('small2');
	var st = document.getElementsByClassName('st');

	small.onmousedown = function(event){
		var x = event.clientX - small.offsetLeft;
		var y = event.clientY - small.offsetTop;

		document.onmousemove = function(event){
			
				var _x = event.clientX;
				var _y = event.clientY;
				small.style.left = _x - x +'px';
				small.style.top = _y - y +'px';

			for (var i = 0; i < st.length; i++) {				
				// 斜边平方
				var rr = Math.pow((small.offsetWidth/2 + st[i].offsetWidth/2),2);
				// 两个直角边分平方
				var toptop = Math.pow(((small.offsetWidth/2 + small.offsetTop) - (st[i].offsetWidth/2 + st[i].offsetTop)),2);
				var leftleft = Math.pow(((small.offsetWidth/2 + small.offsetLeft) - (st[i].offsetWidth/2 + st[i].offsetLeft)),2);				
				if (rr >= toptop + leftleft) {
					st[i].style.backgroundColor = 'yellow';
					break;
				}else{
					st[i].style.backgroundColor = 'red';
				};
			};
		}
	}
	small.onmouseup = function(){
		document.onmousemove = '';
	}
</script>
</html>